from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import GoodCollection
from .utils import check_login
from goods.views import org_json
from goods.models import Goods
import redis
import jwt
from django.conf import settings

# 自定义函数，组织购物出车中商品字典
def org_good_json(cart_key,good_id,num,check=False):
    '''
    :param cart_key: 购物车id 如 cat_1,cat_2......
    :param good_id:  购物车商品的id int
    :param num:  当前商品架构的数量，int
    :param check:  当前商品勾选状态  默认False
    :return:   商品字典列表 如：[{},{},{},{}......]
    '''
    # 根据商品id查询商品对象
    try:
        good = Goods.objects.get(id=good_id)
    except:
        return {}

    return {
        "id": cart_key,
        "productID": good.id,
        "productName": good.sku_name,
        "productImg": good.img,
        "price": good.selling_price,
        "num": num,  # 该商品在购物车中的数量
        'maxNum':good.stock,
        'check':check
    }




# Create your views here.

# class GoodCollectinoAPIView(APIView):
#
#     def post(self,request):
#         good_id = request.data.get('productID')
#         token = request.headers.get('Authorization')
#         print('获取的数据',good_id,'用户',token)
#
#         # 解码token，获取用户信息
#         # 待优化
#         try:
#             payload = jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])
#
#
#         except Exception as e:
#             print('解码错误',e.args)
#             return Request({
#                 'code':401,
#                 'msg':'未认证'
#             })
#
#         # 获取用户的信息
#         print('解码出用户信息',payload)
#         uid = payload.get('uid')
#
#         # 有问题待解决
#         GoodCollection.objects.create(user_id=uid,good_id=good_id)
#
#         return Request({
#             'code':200,
#             'msg':'收藏成功'
#         })

class CollectionAPIView(APIView):
    @check_login
    def post(self,request):
        # 1.接收前端数据
        good_id = request.data.get('productID')
        print('xxx', good_id)

        uid = request.uid
        # 商品去重
        good_collection = GoodCollection.objects.filter(user_id=uid,good_id=good_id)
        if good_collection:
            return Response({
                'code':204,
                'msg':'该商品已经收藏'
            })
        GoodCollection.objects.create(user_id=uid,good_id=good_id)
        return Response({
            'code':200,
            'msg':'收藏成功'
        })

    @check_login
    def get(self,request):
        uid = request.uid

        # 获取当前用户收藏的当前商品

        goods_collection = GoodCollection.objects.filter(user_id=uid)

        # goods = [i.good for i in goods_collection]

        goods = []
        for i in goods_collection:
            xiao = i.good
            goods.append(xiao)


        data = org_json(goods)


        return Response({
            'code':200,
            'msg':'加载收藏数据成功',
            'data':data
        })

    # 删除收藏
    @check_login
    def delete(self,request):
        # 接受商品id
        good_id = request.data.get('productID')
        uid = request.uid

        # 查询收藏的数据

        GoodCollection.objects.filter(user_id=uid,good_id=good_id).delete()
        # 返回响应

        return Response({
            'code':200,
            'msg':'删除收藏成功'
        })



# 购物车加购
class Shopping(APIView):
    @check_login
    def post(self,request):
        # 获取前端商品的id
        good_id = request.data.get('productID')

        # 判断商品是否存在
        good = Goods.objects.filter(id=good_id).first()
        if not good:
            return Response({
                'code':403,
                'msg':'加购商品不存在'
            })

        cart = f'cart_{request.uid}'
        cart_token = f'token_{request.uid}'


        redis_u = redis.Redis(host='localhost',port=6379,db=1,password='123321')


        if good.stock >0:
            # 判断是否第一次加购
            num = redis_u.hget(cart,good_id)
            if num:
                # 第一次加购
                num = int(num.decode()) + 1
                if num <= good.stock:
                    # 可以正常加购
                    redis_u.hset(cart,good_id,num)
                    # 加入集合
                    redis_u.sadd(cart_token,good_id)
                    return Response({
                        'code':201,
                        'msg':'该商品已经在购物车商品加1'
                    })
                else:
                    # 不可以加购
                    return Response({
                        'code':202,
                        'msg':'加购数量达到限制'
                    })
            else:
                # 第一次加购
                redis_u.hset(cart,good_id,1)
                redis_u.sadd(cart_token,good_id)

                return Response({
                    'code':200,
                    'msg':'新加入购物车成功',
                    'shoppingCartData':{
                        "id": cart,
                        "productID": good.id,
                        "productName": good.sku_name,
                        "productImg": good.img,
                        "price": good.selling_price,
                        "num": 1,  # 该商品在购物车中的数量
                        'maxNum':good.stock,
                        'check':True

                    }
                })

        else:
            return Response({
                'code':403,
                'msg':'没有库存，无法购买'
            })


    # 加载购物车的数据

    @check_login
    def get(self,request):
        uid = request.uid

        # 构造redis中的key
        redis_conn = redis.Redis(host='localhost',port=6379,db=1,password='123321')
        cart_key = 'cart_%s'%uid
        cart_selected_key = 'cart_selected_%s'%uid
        print('小达达',cart_key,'达达',cart_selected_key)


        # 查询购物车数据

        cart_selected_data = [int(i.decode()) for i in redis_conn.smembers(cart_selected_key)]

        cart_data = redis_conn.hgetall(cart_key)
        print(cart_data, 'data数据')
        print(cart_selected_data, 'data数据')
        # 初始化一个空列表，为了存储所有的购物车商品字典
        shopping_cart_data = []
        for good_id, num in cart_data.items():
            # 数据类型转换 字节串---转为整形
            good_id = int(good_id.decode())
            num = int(num.decode())

            # 组织商品json数据
            if good_id in cart_selected_data:
                # 当前商品为勾选状态
                data = org_good_json(cart_key,good_id,num,check = True)

            else:
                # 当前商品未勾选状态
                data = org_good_json(cart_key,good_id,num, check = False)

            # 将商品字典追加到列表
            shopping_cart_data.append(data)


        return Response({
            'code':200,
            'msg':'加载购物车商品成功',
            'setShoppingCartData':shopping_cart_data
        })

    # 更新购物车
    @check_login
    def put(self,request):
        uid = request.uid
        # 创造redis中的key
        cart_key = 'cart_%s' % uid
        cart_selected_key = 'cart_selected_%s' % uid
        # 接受前端数据
        good_id = request.data.get('productID')
        current_value = request.data.get('currentValue')
        redis_conn = redis.Redis(host='localhost', port=6379, db=1, password='123321')
        label = request.data.get('label')
        val = request.data.get('val')
        print(val,'dadadaw')
        print('接受的前端跟新数据',good_id,'x',current_value,'w',uid,'la',label,'val',val)

        if label == 'singleNumber':

            redis_conn.hset(cart_key,good_id,current_value)

            redis_conn.sadd(cart_selected_key,good_id)

            return Response({
                'code':200,
                'msg':'更新购物车成功'
            })
        elif label == 'singleSelected':
            if val:
                # 设置选择
                redis_conn.sadd(cart_selected_key,good_id)

            else:
                # 取消选中
                redis_conn.srem(cart_selected_key,good_id)

            return Response({
                'code':200,
                'msg':'已选中' if val else '已取消'
            })
        elif label == 'allsingle':
            if val:
                # 需要全选, 即将哈希结构中所有的key加入到集合中
                # 获取哈希中所有的key  返回的是一个列表
                good_ids = redis_conn.hkeys(cart_key)
                # 将所有的key加入集合  *good_ids : *是解包
                redis_conn.sadd(cart_selected_key,*good_ids)

            else:
                # 取消全选 ， 将集合中所有的商品id删除
                ...
                redis_conn.delete(cart_selected_key)

            return Response({
                'code':200,
                'msg':'以全选' if val else '已取消'
            })

    @check_login
    def delete(self,request):
        good_id = request.data.get('productID')
        uid = request.uid

        print('商品id',good_id)

        # 连接rdids
        redis_conn = redis.Redis(host='localhost',db=1,port=6379,password='123321')

        # 定义key
        conn_key = 'cart_%s'%uid
        conn_selected_key = 'cart_selected_%s'%uid

        # 将key删除
        # 删除商品数量  删除哈希数据
        redis_conn.hdel(conn_key,good_id)
        # 删除商品的id  删除集合数据
        redis_conn.srem(conn_selected_key,good_id)

        return Response({
            'code':200,
            'msg':'删除成功'
        })



















